<?php
/**
 * KidsMind Dynamic Cognitive Module Page
 * 
 * This file displays a cognitive module by fetching data from the API
 * URL format: cognitive-module.php?module=colors&age=3-4
 */

// Get module slug and age from URL
$module_slug = isset($_GET['module']) ? $_GET['module'] : '';
$age_group = isset($_GET['age']) ? $_GET['age'] : '3-4';

// Validate input
if (empty($module_slug)) {
    die('Error: Module slug is required');
}

// Validate age group
$valid_ages = ['3-4', '5-6', '7-8'];
if (!in_array($age_group, $valid_ages)) {
    $age_group = '3-4'; // Default to 3-4 if invalid
}

// Fetch module data from API
$module_url = "api/cognitive.php?action=module&slug={$module_slug}&age={$age_group}";
$module_json = file_get_contents($module_url);
$module_data = json_decode($module_json, true);

// Check if module was found
if (!isset($module_data['status']) || $module_data['status'] !== 'success') {
    die('Error: Module not found');
}

$module = $module_data['data'];

// Fetch module items from API
$items_url = "api/cognitive.php?action=items&module={$module_slug}&age={$age_group}";
$items_json = file_get_contents($items_url);
$items_data = json_decode($items_json, true);

// Check if items were found
if (!isset($items_data['status']) || $items_data['status'] !== 'success') {
    die('Error: Failed to fetch module items');
}

$items = $items_data['data'];

// Page title and meta tags
$page_title = $module['name'] . ' - ' . $age_group . '岁专区 - KidsMind';
$meta_description = $module['description'];

// Generate gradient based on module color
$color_hex = $module['color_hex'];
$color_lighter = adjustBrightness($color_hex, 30);
$color_darker = adjustBrightness($color_hex, -20);

// Function to adjust color brightness
function adjustBrightness($hex, $steps) {
    // Extract RGB values
    $hex = ltrim($hex, '#');
    $r = hexdec(substr($hex, 0, 2));
    $g = hexdec(substr($hex, 2, 2));
    $b = hexdec(substr($hex, 4, 2));
    
    // Adjust brightness
    $r = max(0, min(255, $r + $steps));
    $g = max(0, min(255, $g + $steps));
    $b = max(0, min(255, $b + $steps));
    
    // Convert back to hex
    return sprintf('#%02x%02x%02x', $r, $g, $b);
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?></title>
    <meta name="description" content="<?php echo $meta_description; ?>">
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/styles.css">
    <style>
        /* Module specific styles */
        body {
            background: linear-gradient(135deg, <?php echo $color_hex; ?>, <?php echo $color_lighter; ?>, #FFFFFF, <?php echo $color_lighter; ?>, <?php echo $color_hex; ?>);
            background-size: 600% 600%;
            animation: gradientBG 60s ease infinite;
            font-family: 'Comic Sans MS', 'Marker Felt', 'Arial Rounded MT Bold', sans-serif;
        }
        
        @keyframes gradientBG {
            0% { background-position: 0% 50% }
            50% { background-position: 100% 50% }
            100% { background-position: 0% 50% }
        }
        
        .navbar {
            background: linear-gradient(to right, <?php echo $color_hex; ?>, <?php echo $color_darker; ?>);
            border-radius: 0 0 20px 20px;
        }
        
        .module-header {
            text-align: center;
            margin: 20px 0 30px;
            background-color: rgba(255, 255, 255, 0.8);
            padding: 20px;
            border-radius: 20px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }
        
        .module-header h1 {
            color: <?php echo $color_darker; ?>;
            font-size: 2.5rem;
            font-weight: bold;
            margin-bottom: 15px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
        }
        
        .module-header p {
            color: #555;
            font-size: 1.2rem;
            margin-bottom: 0;
        }
        
        .module-container {
            background-color: #fff;
            border-radius: 20px;
            padding: 25px;
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
            margin-bottom: 30px;
            transition: transform 0.3s ease, box-shadow 0.3s ease;
            position: relative;
            overflow: hidden;
        }
        
        .module-container:hover {
            transform: translateY(-5px);
            box-shadow: 0 12px 30px rgba(0, 0, 0, 0.15);
        }
        
        .module-row {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .module-sample {
            width: 120px;
            height: 120px;
            border-radius: 15px;
            margin-right: 25px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            flex-shrink: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.8rem;
            font-weight: bold;
            color: white;
            text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.3);
            background-color: <?php echo $color_hex; ?>;
            cursor: pointer;
            border: 4px solid white;
            transition: all 0.3s ease;
        }
        
        .module-sample:hover {
            transform: scale(1.05);
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
        }
        
        .module-images {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
        }
        
        .module-image {
            width: 120px;
            height: 120px;
            border-radius: 15px;
            object-fit: cover;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
            cursor: pointer;
            border: 3px solid white;
            transition: all 0.3s ease;
        }
        
        .module-image:hover {
            transform: scale(1.05);
            box-shadow: 0 6px 15px rgba(0, 0, 0, 0.15);
        }
        
        .module-info {
            background-color: rgba(255, 255, 255, 0.8);
            padding: 20px;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
            margin-top: 20px;
            margin-bottom: 20px;
            display: none;
        }
        
        .module-info h4 {
            margin-bottom: 15px;
            color: #444;
            font-weight: bold;
        }
        
        .module-info p {
            color: #666;
            margin-bottom: 10px;
        }
        
        .module-title {
            font-weight: bold;
            font-size: 1.8rem;
            color: #333;
            margin-bottom: 15px;
            border-bottom: 2px dashed rgba(0,0,0,0.1);
            padding-bottom: 10px;
        }
        
        .navigation-container {
            display: flex;
            justify-content: space-between;
            margin-top: 30px;
            margin-bottom: 30px;
        }
        
        .navigation-btn {
            padding: 10px 20px;
            border-radius: 30px;
            background-color: <?php echo $color_hex; ?>;
            color: white;
            text-decoration: none;
            font-weight: bold;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
        }
        
        .navigation-btn:hover {
            background-color: <?php echo $color_darker; ?>;
            transform: translateY(-3px);
            box-shadow: 0 6px 15px rgba(0, 0, 0, 0.15);
            color: white;
        }
        
        .navigation-btn.home {
            background-color: #2196F3;
        }
        
        .navigation-btn.home:hover {
            background-color: #1976D2;
        }
        
        .module-encyclopedia {
            background-color: rgba(255, 255, 255, 0.9);
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
            margin-top: 40px;
            margin-bottom: 30px;
            position: relative;
        }
        
        .modal-fullscreen-image {
            text-align: center;
        }
        
        .modal-fullscreen-image img {
            max-height: 80vh;
            max-width: 100%;
        }
        
        .module-image {
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .module-image:hover {
            transform: scale(1.05);
            box-shadow: 0 6px 15px rgba(0, 0, 0, 0.15);
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-light">
        <div class="container">
            <a class="navbar-brand" href="index.html">
                <img src="images/logo.png" alt="KidsMind Logo" width="40" height="40" class="d-inline-block align-top">
                KidsMind
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="index.html">首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="age-<?php echo $age_group; ?>.html"><?php echo $age_group; ?>岁专区</a>
                    </li>
                    <?php 
                    // Generate links for other age groups
                    foreach ($valid_ages as $age) {
                        if ($age != $age_group) {
                            echo '<li class="nav-item">';
                            echo '<a class="nav-link" href="age-' . $age . '.html">' . $age . '岁专区</a>';
                            echo '</li>';
                        }
                    }
                    ?>
                    <li class="nav-item">
                        <a class="nav-link" href="login.html">登录</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
    
    <div class="container">
        <!-- 页面标题 -->
        <div class="module-header">
            <h1><?php echo $module['name']; ?></h1>
            <p><?php echo $module['description']; ?></p>
        </div>
        
        <?php foreach ($items as $item): ?>
        <!-- <?php echo $item['name']; ?>类别 -->
        <div class="module-container">
            <h3 class="module-title"><?php echo $item['name']; ?></h3>
            <div class="module-row">
                <div class="module-sample">
                    <?php echo $item['name']; ?>
                </div>
                <div>
                    <p><?php echo $item['content']; ?></p>
                    <button class="btn btn-outline-primary mb-3" onclick="toggleInfo('item-<?php echo $item['id']; ?>-info')">了解更多</button>
                    <div id="item-<?php echo $item['id']; ?>-info" class="module-info">
                        <h4><?php echo $item['name']; ?>的特点：</h4>
                        <?php 
                        // Display additional info as bullet points if available
                        if (!empty($item['additional_info'])) {
                            $points = explode(';', $item['additional_info']);
                            foreach ($points as $point) {
                                echo '<p>- ' . trim($point) . '</p>';
                            }
                        }
                        ?>
                    </div>
                </div>
            </div>
            <div class="module-images">
                <?php
                // Fetch item images from database
                $sql = "SELECT image_path, title, description, is_thumbnail, display_order 
                        FROM km_cognitive_item_images 
                        WHERE item_id = ? 
                        ORDER BY display_order ASC";
                $stmt = $conn->prepare($sql);
                $stmt->bind_param('i', $item['id']);
                $stmt->execute();
                $images_result = $stmt->get_result();

                if ($images_result->num_rows > 0) {
                    // We have images stored in the database
                    while ($image = $images_result->fetch_assoc()) {
                        $alt_text = !empty($image['title']) ? $image['title'] : $item['name'];
                        echo '<img src="' . $image['image_path'] . '" alt="' . htmlspecialchars($alt_text) . '" ';
                        echo 'class="module-image" title="' . htmlspecialchars($alt_text) . '">';
                    }
                } else {
                    // Fallback to legacy method (4 numbered images)
                    // Extract the base image path and try to find 4 images
                    $base_image_path = $item['image_path'];
                    $image_name = basename($base_image_path);
                    $image_dir = dirname($base_image_path);
                    $image_name_parts = explode('-', $image_name);
                    $image_base_name = $image_name_parts[0];
                    $image_extension = pathinfo($image_name, PATHINFO_EXTENSION);
                    
                    // Generate image paths 1-4
                    for ($i = 1; $i <= 4; $i++) {
                        $img_path = $image_dir . '/' . $image_base_name . '-' . $i . '.' . $image_extension;
                        $alt_text = $item['name'] . ' ' . $i;
                        echo '<img src="' . $img_path . '" alt="' . htmlspecialchars($alt_text) . '" class="module-image">';
                    }
                }
                ?>
            </div>
        </div>
        <?php endforeach; ?>
        
        <!-- 模块百科 -->
        <div class="module-encyclopedia">
            <h3 class="text-center mb-4"><?php echo $module['name']; ?>小百科</h3>
            <div class="row">
                <div class="col-md-12">
                    <p><?php echo $module['introduction']; ?></p>
                </div>
            </div>
        </div>
        
        <!-- 导航按钮 -->
        <div class="navigation-container">
            <a href="age-<?php echo $age_group; ?>-cognitive.html" class="navigation-btn home">返回认知主页</a>
            <?php 
            // If a next module is available, link to it
            // This would need to be dynamically determined based on module order
            // For simplicity, we'll just link back to the cognitive page
            ?>
        </div>
    </div>
    
    <script src="js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script>
        function toggleInfo(id) {
            const element = document.getElementById(id);
            if (element.style.display === "block") {
                element.style.display = "none";
            } else {
                element.style.display = "block";
            }
        }

        $(document).ready(function() {
            // Add click handler for module images
            $('.module-image').on('click', function() {
                const largeImageUrl = $(this).data('large-image') || $(this).attr('src');
                const imageTitle = $(this).attr('alt');
                
                // Create modal with large image
                const modal = `
                    <div class="modal fade" id="imageModal" tabindex="-1" aria-hidden="true">
                        <div class="modal-dialog modal-xl">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title">${imageTitle}</h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                </div>
                                <div class="modal-body modal-fullscreen-image">
                                    <img src="${largeImageUrl}" class="img-fluid rounded" alt="${imageTitle}">
                                </div>
                            </div>
                        </div>
                    </div>
                `;
                
                // Remove existing modal if any
                $('#imageModal').remove();
                
                // Add modal to body and show it
                $('body').append(modal);
                const imageModal = new bootstrap.Modal(document.getElementById('imageModal'));
                imageModal.show();
            });
        });
    </script>
</body>
</html> 